import React,{Component} from 'react';
import { StyleSheet, Text,Button,Alert, View } from 'react-native';

function Square (props) {
  return(
    <View style={styles.square}>
      <Text onPress={props.onPress} style={styles.cell}>{props.value}</Text>
    </View>
  )
}

class Board extends Component{
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onPress={()=>this.props.onPress(i)}
      />
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.boardRow}>
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </View>
        <View style={styles.boardRow}>
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </View>
        <View style={styles.boardRow}>
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </View>
      </View>
    );
  }
}

class Game extends Component{
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true
    };
  }
  _handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();

    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([
        {
          squares: squares
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext
    });
  }

  _rePlayGame(){
    this.setState({
      history: [
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true
    })
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((move,step)=>{
      const desc = step?
        '跳跃到第'+step+'步':
        '游戏开始';
      return(
        <View style={{marginBottom:10}} key={step}>
          <Text onPress={()=>this.jumpTo(step)}>{step+1}. {desc}</Text>
        </View>
      )
    })
    let status;

    if(winner){
      status = 'Winner: ' + winner;
    }else{
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }
    return (
      <View style={{marginLeft:20}}>
        <Text style="status">{status}</Text>
        <View style={{flexDirection: 'row',alignItems:'center',justifyContent:'space-around'}}>
          <View>
            <Board
              squares={current.squares}
              onPress={(i)=>this._handleClick(i)}
            />
          </View>
          <View style={{marginLeft:20}}>
            { this.state.history.length>1? <View style={styles.resetBtn}><Text onPress={()=>this._rePlayGame()} style={styles.btnText}>重新开始</Text></View> : null }
            <View>{moves}</View>
          </View>
        </View>
      </View>
    )
  }
}

export default function App() {
  return (
    <View style={{flex:1,alignItems:'flex-start',justifyContent: 'center'}}>
      <Game />
    </View>
  );
}

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    marginTop:40,
    justifyContent: 'flex-start',
    borderWidth: 1,
    borderColor: "#000",
    borderBottomWidth:0,
    borderRightWidth:0,
    textAlign: 'center',
    width:180,
    height:184
  },
  boardRow:{
    flexDirection: "row",
    borderBottomColor: '#000',
    borderBottomWidth: 1,
  },
  square:{
    width:60,
    height:60,
    backgroundColor:'#fff',
    borderRightWidth: 1,
    borderRightColor: "#000",
  },
  cell:{
    textAlign: 'center',
    width:59,
    height:60,
    lineHeight:50,
    backgroundColor: '#eee'
  },
  resetBtn:{
    backgroundColor:'#ddd',
    width:90,
    height:40,
    borderRadius:20,
    marginBottom:10
  },
  btnText:{
    fontSize:12,
    color:'#000',
    textAlign:'center',
    lineHeight:32,
  }


});
